package net.wanho.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.common.RoleConstant;
import net.wanho.common.UserConstant;
import net.wanho.dto.RoleDTO;
import net.wanho.dto.RoleExportDTO;
import net.wanho.mapper.RoleMapper;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.mapper.UserRoleMapper;
import net.wanho.po.Role;
import net.wanho.po.UserInfo;
import net.wanho.po.UserRole;
import net.wanho.service.RoleService;
import net.wanho.vo.PageInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 32033
 * @description 针对表【role(角色表)】的数据库操作Service实现
 * @createDate 2025-01-11 17:01:23
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    private final UserRoleMapper userRoleMapper;
    private final UserInfoMapper userInfoMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Role> getUserRoleList(Integer userId) {
        List<UserRole> list;
        try {
            list = userRoleMapper.selectUserById(userId);
        } catch (Exception e) {
            return null;
        }
        System.out.println(list);
        List<Role> roles = this.listByIds(list.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
        //从redis里取出userid
        Integer userid = (Integer) redisTemplate.opsForValue().get("token");
        //从redis里删除菜单
        redisTemplate.delete(UserConstant.MENU_PREFIX + userid);
        return roles;
    }

    @Override
    public PageInfo<Role> getRolePageList(Integer pageNum, Integer pageSize, RoleDTO roleDTO) {
        Page<Role> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(!org.springframework.util.ObjectUtils.isEmpty(roleDTO.getRoleName()), "role_name", roleDTO.getRoleName());
        wrapper.eq(!org.springframework.util.ObjectUtils.isEmpty(roleDTO.getRoleCode()), "role_code", roleDTO.getRoleCode());
        wrapper.eq(!org.springframework.util.ObjectUtils.isEmpty(roleDTO.getRoleState()), "role_state", roleDTO.getRoleState());

        Page<Role> rolePage = this.baseMapper.selectPage(page, wrapper);

        // 查询后 设置创建人用户名
        rolePage.getRecords().forEach(role -> {
            if (role.getCreateBy() != null) {
                UserInfo userInfo = userInfoMapper.selectById(role.getCreateBy());
                if (userInfo != null) {
                    role.setGetCode(userInfo.getUserName());
                }
            }
        });

        PageInfo<Role> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setTotalNum(page.getTotal());
        pageInfo.setPageCount(page.getCurrent());
        pageInfo.setResultList(page.getRecords());
        pageInfo.setLimitIndex(page.offset());
        return pageInfo;
    }

    @Override
    public List<Role> exportTable(RoleExportDTO roleExportDTO) {
//        Page<Role> page = new Page<>(pageNum, pageSize);
//        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(!ObjectUtils.isEmpty(role.getRoleName()), Role::getRoleName, role.getRoleName());
//        wrapper.like(!ObjectUtils.isEmpty(role.getRoleCode()), Role::getRoleCode, role.getRoleCode());
//        wrapper.like(!ObjectUtils.isEmpty(role.getRoleState()), Role::getRoleState, role.getRoleState());
//        this.page(page, wrapper);
//        return page.getRecords();

        // TODO 优化代码 多看看
        // 构建查询条件
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(roleExportDTO.getRoleCode()), Role::getRoleCode, roleExportDTO.getRoleCode())
                .like(StringUtils.hasText(roleExportDTO.getRoleName()), Role::getRoleName, roleExportDTO.getRoleName())
                .like(StringUtils.hasText(roleExportDTO.getRoleState()), Role::getRoleState, roleExportDTO.getRoleState())
                .orderByAsc(Role::getRoleId);

        // 执行分页查询
        Page<Role> page = new Page<>(roleExportDTO.getPageNum(), roleExportDTO.getPageSize());
        Page<Role> rolePage = this.page(page, wrapper);

        // 获取结果列表
        List<Role> roleList = rolePage.getRecords();

        // 设置创建人用户名
        if (!CollectionUtils.isEmpty(roleList)) {
            // 收集所有创建人ID
            Set<Integer> createByIds = roleList.stream()
                    .map(Role::getCreateBy)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            if (!CollectionUtils.isEmpty(createByIds)) {
                // 批量查询用户信息
                Map<Integer, String> createByMap = userInfoMapper.selectBatchIds(createByIds)
                        .stream()
                        .collect(Collectors.toMap(UserInfo::getUserId, UserInfo::getUserCode));
                // 设置创建人用户名
                roleList.forEach(role -> {
                    role.setGetCode(createByMap.get(role.getCreateBy()));
                });
            }
        }
        return roleList;
    }

    @Override
    public void addRole(Role role) {
        Role baseRole = userRoleMapper.selectRoleByName(role.getRoleName());
        if (baseRole != null) {
            throw new RuntimeException("角色已存在");
        }
        // 默认状态
        role.setRoleState(RoleConstant.ROLE_STATE);
        // 创建时间
        role.setCreateTime(new Date());
        // 创建人id
        role.setCreateBy(Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("token")).toString()));
        this.baseMapper.insert(role);
    }

    @Override
    public Role selectRoleById(Integer id) {

        return userRoleMapper.selectRoleById(id);
    }

}




